package com.factory.iamp.utils.helper;

import com.factory.iamp.utils.exception.APIException;
import lombok.Getter;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLDecoder;
import java.util.UUID;

@Component
public class FileUploadHelper {
    @Getter
    private final static String basePath = System.getProperty("user.dir");

    public static boolean mkPath(String filePath) {
        StringBuilder fPath = new StringBuilder(basePath);
        for(String fname: filePath.split("[/\\\\]")){
            fPath.append("/").append(fname);
            File dest = new File(fPath.toString());
            if((!dest.exists()) && (!dest.mkdir())) return false;
        }
        return true;
    }

    public static File uploadedFile(String path, MultipartFile file) throws Throwable {
        String originName = file.getOriginalFilename();
        assert originName != null;
        String fileExtension = originName.substring(originName.lastIndexOf("."));
        String serverName = UUID.randomUUID() + fileExtension;
        return upload(path, serverName, file);
    }

    public static String uploadedPath(String path, MultipartFile file) throws Throwable {
        File savedFile = uploadedFile(path, file);
        return makeFilePath(savedFile);
    }

    public static String makeFilePath(File file) {
        return file.getPath().replace(basePath, "").replace("\\", "/");
    }

    public static String upload_sign(int tid, MultipartFile file) throws Throwable {
        return uploadedPath("/data/sign/" + tid + "/", file);
    }

    public static File upload(String filePath, String serverName, MultipartFile file) throws Throwable {
        String fileDir = URLDecoder.decode(basePath + filePath, "UTF-8");
        if(!mkPath(filePath)) throw new APIException(ResponseCode.SERVER_FAILED, "创建路径失败");
        File dest = new File(fileDir + serverName);
        file.transferTo(dest);
        return dest;
    }

    public static void deleteFile(String filePath) {
        File data = new File(basePath + filePath);
        if(!data.delete()) throw new APIException(ResponseCode.SERVER_FAILED, "文件删除失败");
    }
}
